<template>
  <view class="detail-page">
    <!-- 订单状态 -->
    <view class="status-section" :class="`status-${orderInfo.status}`">
      <view class="status-icon">
        <uni-icons 
          :type="getStatusIcon()" 
          size="60" 
          color="#fff"
        ></uni-icons>
      </view>
      <text class="status-text">{{ orderInfo.statusText }}</text>
      <text v-if="orderInfo.status === 'unpaid'" class="status-tip">
        请在15分钟内完成支付
      </text>
    </view>

    <!-- 配送信息 -->
    <view class="address-section">
      <view class="section-header">
        <uni-icons type="location-filled" size="18" color="#00C853"></uni-icons>
        <text class="section-title">配送信息</text>
      </view>
      <view class="address-info">
        <view class="contact-row">
          <text class="contact-name">{{ orderInfo.contactName }}</text>
          <text class="contact-phone">{{ orderInfo.contactPhone }}</text>
        </view>
        <text class="address-text">{{ orderInfo.address }}</text>
      </view>
    </view>

    <!-- 商家信息 -->
    <view class="merchant-section">
      <text class="merchant-name">{{ orderInfo.merchantName }}</text>
      <text class="order-time">下单时间: {{ orderInfo.createTime }}</text>
    </view>

    <!-- 商品列表 -->
    <view class="goods-section">
      <view 
        v-for="item in orderInfo.items" 
        :key="item.id"
        class="goods-item"
      >
        <image :src="item.image" class="goods-image"></image>
        <view class="goods-info">
          <text class="goods-name">{{ item.name }}</text>
          <text v-if="item.specs" class="goods-specs">{{ item.specs }}</text>
        </view>
        <view class="goods-right">
          <text class="goods-price">¥{{ item.price }}</text>
          <text class="goods-count">x{{ item.count }}</text>
        </view>
      </view>
    </view>

    <!-- 费用明细 -->
    <view class="fee-section">
      <view class="fee-row">
        <text class="fee-label">商品金额</text>
        <text class="fee-value">¥{{ orderInfo.goodsAmount }}</text>
      </view>
      <view class="fee-row">
        <text class="fee-label">配送费</text>
        <text class="fee-value">¥{{ orderInfo.deliveryFee }}</text>
      </view>
      <view class="fee-row total">
        <text class="fee-label">实付</text>
        <text class="fee-value">¥{{ orderInfo.totalAmount }}</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="info-row">
        <text class="info-label">订单编号</text>
        <text class="info-value">{{ orderInfo.orderNo }}</text>
      </view>
      <view class="info-row">
        <text class="info-label">支付方式</text>
        <text class="info-value">{{ orderInfo.paymentMethodText }}</text>
      </view>
      <view v-if="orderInfo.remark" class="info-row">
        <text class="info-label">备注</text>
        <text class="info-value">{{ orderInfo.remark }}</text>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view v-if="orderInfo.status === 'unpaid'" class="action-bar">
      <view class="cancel-btn" @tap="cancelOrder">取消订单</view>
      <view class="pay-btn" @tap="payOrder">立即支付</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getOrderDetail } from '@/api/order';

// 订单信息
const orderInfo = ref({
  id: 0,
  orderNo: '',
  status: 'unpaid', // unpaid待支付 paid已支付 delivering配送中 completed已完成 cancelled已取消
  statusText: '待支付',
  merchantName: '',
  contactName: '',
  contactPhone: '',
  address: '',
  createTime: '',
  paymentMethodText: '',
  remark: '',
  goodsAmount: 0,
  deliveryFee: 0,
  totalAmount: 0,
  items: [] as Array<{
    id: number;
    name: string;
    specs?: string;
    image: string;
    price: number;
    count: number;
  }>
});

// 页面加载
onLoad(async (options: any) => {
  console.log('订单详情页面加载,参数:', options);
  
  if (options.id) {
    await loadOrderDetail(Number(options.id));
  } else {
    uni.showToast({
      title: '订单信息不完整',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 加载订单详情
const loadOrderDetail = async (orderId: number) => {
  try {
    uni.showLoading({ title: '加载中...' });
    
    const result = await getOrderDetail(orderId.toString());
    console.log('订单详情', result)
    
    const orderData = result.data?.order || result.order;
    const itemsData = result.data?.items || result.items || [];
    
    if (!orderData) {
      throw new Error('订单数据为空');
    }
    
    // 解析地址快照
    let addressData: any = {};
    try {
      addressData = JSON.parse(result.addressSnapshot || '{}');
    } catch (e) {
      console.error('解析地址失败:', e);
    }
    
    // 状态映射
    const statusMap: Record<number, { key: string; text: string }> = {
      1: { key: 'unpaid', text: '待支付' },
      2: { key: 'paid', text: '已支付' },
      3: { key: 'delivering', text: '配送中' },
      4: { key: 'completed', text: '已完成' },
      5: { key: 'cancelled', text: '已取消' }
    };
    
    const statusInfo = statusMap[result.status] || statusMap[1];
    
    // 支付方式映射
    const paymentMap: Record<number, string> = {
      1: '微信支付',
      2: '支付宝',
      3: '余额支付'
    };
    
    // 映射数据
    orderInfo.value = {
      id: orderData.orderId,
      orderNo: orderData.orderNumber,
      status: statusInfo.key,
      statusText: statusInfo.text,
      merchantName: orderData.merchantName || '商家名称',
      contactName: addressData.contactName || '',
      contactPhone: addressData.contactPhone || '',
      address: `${addressData.province || ''}${addressData.city || ''}${addressData.district || ''}${addressData.street || ''}`,
      createTime: orderData.createTime || '',
      paymentMethodText: paymentMap[orderData.paymentMethod] || '未知',
      remark: orderData.remark || '',
      goodsAmount: orderData.totalAmount - 3, // 假设配送费3元
      deliveryFee: 3,
      totalAmount: orderData.totalAmount,
      items: itemsData.map((item: any) => ({
        id: item.productId,
        name: item.productName,
        specs: item.tasteOptions,
        image: item.productImage || '/static/food01.png',
        price: item.unitPrice,
        count: item.quantity
      }))
    };
    
    console.log('订单详情加载成功:', orderInfo.value);
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    console.error('加载订单失败:', error);
    uni.showToast({
      title: '加载订单失败',
      icon: 'none'
    });

    // 模拟数据
    orderInfo.value = {
      id: orderId,
      orderNo: `202401${orderId}`,
      status: 'unpaid',
      statusText: '待支付',
      merchantName: '超级麻辣小面家馆',
      contactName: '张三',
      contactPhone: '138****5678',
      address: '贵州省贵阳市观山湖区大数据科创城1栋',
      createTime: '2024-01-15 12:30',
      paymentMethodText: '微信支付',
      remark: '少放辣 | 餐具1份',
      goodsAmount: 26.6,
      deliveryFee: 3,
      totalAmount: 29.6,
      items: [
        {
          id: 1,
          name: '麻辣小面200g套餐',
          specs: '中份 / 中辣',
          image: '/static/food01.png',
          price: 15.8,
          count: 1
        },
        {
          id: 2,
          name: '麻辣小面200g',
          image: '/static/food02.png',
          price: 10.8,
          count: 1
        }
      ]
    };
  }
};

// 获取状态图标
const getStatusIcon = () => {
  const iconMap: Record<string, string> = {
    unpaid: 'wallet',
    paid: 'checkmarkempty',
    delivering: 'navigate',
    completed: 'checkmarkempty',
    cancelled: 'closeempty'
  };
  return iconMap[orderInfo.value.status] || 'wallet';
};

// 取消订单
const cancelOrder = () => {
  uni.showModal({
    title: '提示',
    content: '确定要取消订单吗?',
    success: (res) => {
      if (res.confirm) {
        // TODO: 调用取消订单API
        uni.showToast({ title: '已取消', icon: 'success' });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    }
  });
};

// 支付订单
const payOrder = () => {
  console.log('重新发起支付');
  
  // 重新发起支付
  uni.showLoading({ title: '正在支付...' });
  
  setTimeout(() => {
    uni.hideLoading();
    
    const paySuccess = Math.random() > 0.3;
    
    if (paySuccess) {
      uni.showToast({
        title: '支付成功',
        icon: 'success',
        duration: 1500
      });
      
      setTimeout(() => {
        orderInfo.value.status = 'paid';
        orderInfo.value.statusText = '已支付';
      }, 1500);
    } else {
      uni.showToast({
        title: '支付失败,请重试',
        icon: 'none'
      });
    }
  }, 2000);
};
</script>

<style scoped>
.detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 150rpx;
}

/* 订单状态 */
.status-section {
  padding: 60rpx 30rpx;
  text-align: center;
  color: #fff;
}

.status-section.status-unpaid {
  background: linear-gradient(135deg, #FF9800, #FF5722);
}

.status-section.status-paid,
.status-section.status-completed {
  background: linear-gradient(135deg, #00C853, #00E676);
}

.status-section.status-delivering {
  background: linear-gradient(135deg, #2196F3, #03A9F4);
}

.status-section.status-cancelled {
  background: linear-gradient(135deg, #757575, #9E9E9E);
}

.status-icon {
  margin-bottom: 20rpx;
}

.status-text {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.status-tip {
  display: block;
  font-size: 24rpx;
  opacity: 0.8;
}

/* 配送信息 */
.address-section,
.merchant-section,
.goods-section,
.fee-section,
.order-info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.address-info {
  padding-left: 30rpx;
}

.contact-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.contact-name {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.contact-phone {
  font-size: 28rpx;
  color: #666;
}

.address-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
}

/* 商家信息 */
.merchant-name {
  display: block;
  font-size: 30rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

/* 商品列表 */
.goods-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
}

.goods-specs {
  font-size: 24rpx;
  color: #999;
}

.goods-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8rpx;
}

.goods-price {
  font-size: 28rpx;
  color: #ff3b30;
  font-weight: bold;
}

.goods-count {
  font-size: 24rpx;
  color: #999;
}

/* 费用明细 */
.fee-row {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
}

.fee-row.total {
  border-top: 1rpx solid #f0f0f0;
  margin-top: 10rpx;
  padding-top: 20rpx;
}

.fee-label {
  font-size: 28rpx;
  color: #666;
}

.fee-value {
  font-size: 28rpx;
  color: #333;
}

.fee-row.total .fee-value {
  font-size: 32rpx;
  color: #ff3b30;
  font-weight: bold;
}

/* 订单信息 */
.info-row {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 28rpx;
  color: #666;
}

.info-value {
  font-size: 28rpx;
  color: #333;
}

/* 底部操作按钮 */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  gap: 20rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.05);
  z-index: 100;
}

.cancel-btn,
.pay-btn {
  flex: 1;
  padding: 25rpx;
  text-align: center;
  font-size: 28rpx;
  font-weight: bold;
  border-radius: 40rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.pay-btn {
  background-color: #00C853;
  color: #fff;
}
</style>